<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addFormDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolelist" stripe border>
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="it1 in scope.row.perms" :key="it1._id" class="personrow">
              <el-col :span="3">
                <el-tag type="primary" closable @close="delRoleRight(scope.row._id, it1)">{{ it1.permission_name }}</el-tag>
                <i class="el-icon-caret-right icon"></i>
              </el-col>
              <el-col :span="10">
                <el-tag type="success" @close="delRoleRight(scope.row._id, it2)" v-for="it2 in it1.children" :key="it2._id" closable class="sonTag">{{ it2.permission_name }}</el-tag>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引行 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="openEditDialog(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="delRoles(scope.row._id)"></el-button>
            
            <el-tooltip content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-s-tools" @click="openSetRightDialog(scope.row._id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

<!-- 添加表单对话框 -->
    <el-dialog
    title="添加角色"
    :visible.sync="addFormDialogVisible"
    width="50%"
    @close="addFormDialogClosed">
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
      <el-form-item label="角色名称" label-width="100px" prop="roleName">
        <el-input v-model="addForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" label-width="100px" prop="roleDesc">
        <el-input v-model="addForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addFormDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addRole">确 定</el-button>
    </span>
  </el-dialog>

<!-- 修改表单对话框 -->
  <el-dialog
    title="修改角色"
    :visible.sync="editFormDialogVisible"
    width="50%">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
      <el-form-item label="角色名称" label-width="100px" prop="roleName">
        <el-input v-model="editForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" label-width="100px" prop="roleDesc">
        <el-input v-model="editForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editFormDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editRole">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 分配权限对话框 -->
  <el-dialog
    title="分配权限"
    :visible.sync="setRightDialogVislble"
    width="50%">
    <el-tree
    check-strictly
    :data="permlist"
    show-checkbox
    node-key="_id"
    default-expand-all
    :default-checked-keys="selectedRight"
    :props="setPermProp" @check="selectedRightChangeHandle">
  </el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVislble = false">取 消</el-button>
      <el-button type="primary" @click="setRight">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import {getRoleAPI,addRoleApi, delRoleApi, editRoleApi, getOneRoleApi, getPermissionlistApi, getRightApi, deleteRightApi} from '../../api/roleAPI'
export default {
  data(){
    return{
      // 角色列表
      rolelist: [],
      // 添加角色对话框打开关闭
      addFormDialogVisible: false,
      // 添加角色表单
      addForm:{
        roleName:'',
        roleDesc:''
      },
      // 添加校验规则
      addFormRules:{
        roleName:[{required:true, message:"请输入角色名称", trigger:'blur'}],
        roleDesc:[{required:true, message:'请输入角色描述', trigger:'blur'}]
      },
      // 修改角色对话框打开关闭
      editFormDialogVisible: false,
      // 修改表单
      editForm:{
        _id: '',
        roleName: '',
        roleDesc: ''
      },
      // 修改校验规则
      editFormRules:{
        roleName:[{required:true, message:"请输入角色名称", trigger:'blur'}],
        roleDesc:[{required:true, message:'请输入角色描述', trigger:'blur'}]
      },
      // 分配权限对话框打开关闭
      setRightDialogVislble :  false,
      // 已选中的权限
      selectedRight: [],
      // 权限列表
      permlist: [],
      // 展示嵌套权限
      setPermProp:{
        label:'permission_name',
        children: 'children'
      },
      // 当前要分配权限的角色id
      currentRoleId: ''
    }
  },
  mounted(){
    this.getRole()
  },
  methods:{
    // 获取角色列表
    async getRole(){
      let data = await getRoleAPI()
      if (data.status !== 200) return this.$message.error('获取角色列表失败！')
      this.rolelist = data.data
    },
    // 添加角色对话框关闭事件
    addFormDialogClosed(){
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色
    async addRole(){
      this.$refs.addFormRef.validate(async valid=>{
        if(valid){
          let data = await addRoleApi(this.addForm)
          if(data.status !== 200){
            this.addFormDialogVisible = false
            return this.$message.error('添加角色失败！')
          }
          this.$message.success('添加角色成功！')
          this.getRole()
          this.addFormDialogVisible = false
        }
      })
    },
    // 删除角色
    delRoles(id){
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = await delRoleApi(id)
          if (data.status !== 200) return this.$message.error('删除失败！')
          this.$message.success('删除成功！')
          this.getRole()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 打开修改对话框
    openEditDialog(row){
      this.editForm._id = row._id
      this.editForm.roleName = row.roleName
      this.editForm.roleDesc = row.roleDesc
      this.editFormDialogVisible = true
    },
    // 修改角色
    editRole(){
      this.$refs.editFormRef.validate(async valid => {
        if (valid){
          let data = await editRoleApi(this.editForm)
          if(data.status !== 200){
            this.$message.error('修改失败！')
            this.editFormDialogVisible = false
          }
          this.$message.success('修改成功！')
          this.getRole()
          this.editFormDialogVisible = false
        }
      })
    },
    // 打开分配权限对话框
    async openSetRightDialog(_id){
      this.currentRoleId = _id
      // 获取当前角色已有的权限id
      let data = await getOneRoleApi(_id)
      // 获取所有权限树状结构
      let data2 = await getPermissionlistApi()
      // 赋值
      this.permlist = data2.data
      this.selectedRight = []
      data.data.forEach(item => {
        this.selectedRight.push(item.permid._id)
      })
      this.setRightDialogVislble = true
    },
    // 分配权限
    async setRight(){
      let {data} = await getRightApi({roleid:this.currentRoleId,data: this.selectedRight})
      if (data.status !== 201){
        this.$message.error('分配权限失败！')
        return this.setRightDialogVislble = false
      }
      this.$message.success('分配权限成功！')
      this.$bus.$emit('getmenuList')
      this.getRole()
      this.setRightDialogVislble = false
    },
    // 当选中框把被点击时触发的事件
    selectedRightChangeHandle(checkedNodes, checkedKeys){
      this.selectedRight = checkedKeys.checkedKeys
    },

    // 通过tag标签关闭事件删除角色权限
    async delRoleRight(roleid, perm){
      let rightlist = []
      if (perm.permission_level === 0){
        rightlist.push(perm._id)
        perm.children.forEach((item) => {
          rightlist.push(item._id)
        })
      }else{
        rightlist.push(perm._id)
      }
      let {data} = await deleteRightApi({rightlist, roleid})
      if (data.status !== 200) return this.$message.error('删除失败！')
      this.$message.success('删除成功！')
      this.$bus.$emit('getmenuList')
      this.getRole()
    }
  }
}
</script>

<style scoped>
  .sonTag{
    margin: 0 10px;
  }

  .personrow{
    border-bottom: 1px solid #eee;
    height: 60px;
    display: flex;
    align-items: center;
    padding: 0 20px;
  }
  .personrow:last-child{
    border-bottom: none;
  }
  .icon{
    margin-left: 10px ;
  }
</style>